package cn.com.common.tools;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	/**
	 * set cookie
	 * @param response
	 * @param name
	 * @param value
	 * @param maxage
	 * @return cookie set state
	 */
	public static String setCookie(HttpServletResponse response, String name,
			String value, Integer maxage) {
		try {
			value = URLEncoder.encode(value, "utf-8");
		} catch (UnsupportedEncodingException e) {
		}
		Cookie cookie = new Cookie(name, value);
		if (maxage > 0) {
			cookie.setMaxAge(maxage);
		}
		cookie.setPath("/");
		response.addCookie(cookie);
		return "ok";
	}

	/**
	 * get cookie value
	 * @param request
	 * @param indexname
	 * @return result cookie value
	 */
	public static String getCookie(HttpServletRequest request, String indexname) {
		Cookie[] cookies = request.getCookies();
		
		String cookieValue = "";
		if(cookies==null){
			return cookieValue;
		}
		for (Cookie cookie : cookies) {
			String cname = cookie.getName();
			if (cname.equals(indexname)) {
				cookieValue = cookie.getValue();
				try {
					cookieValue = URLDecoder.decode(cookieValue, "utf-8");
					return cookieValue;
				} catch (UnsupportedEncodingException e) {
				}
				break;
			}
		}
		return cookieValue;
	}

	/**
	 * delete cookie
	 * @param request
	 * @param response
	 * @param indexname
	 * @return delete state
	 */
	public static String delCookie(HttpServletResponse response,
			String indexname) {
		Cookie cookie = new Cookie(indexname, null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
		return "ok";
	}

	/**
	 * delete all cookie
	 * 
	 * @param request
	 * @param response
	 * @param indexname
	 * @return delete state
	 */
	public static String delAllCookie(HttpServletRequest request,
			HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		if (cookies == null || cookies.length <= 0) {
			return "false";
		}
		for (Cookie cookie : cookies) {
			cookie.setValue(null);
			cookie.setMaxAge(0);
			cookie.setPath("/");
			response.addCookie(cookie);
		}
		return "ok";
	}

	/**
	 * get cookie map
	 * @param request
	 * @return cookie map
	 */
	public static Map<String, String> getCookieMap(HttpServletRequest request) {
		Map<String, String> cookieMap = new HashMap<String, String>();
		Cookie[] cookies = request.getCookies();
		if (cookies == null || cookies.length <= 0) {
			return cookieMap;
		}
		for (Cookie cookie : cookies) {
		    String cookieValue=cookie.getValue();
		    try {
				cookieValue=  URLDecoder.decode(cookieValue, "utf-8");
			} catch (UnsupportedEncodingException e) {
				//e.printStackTrace();
			}
			cookieMap.put(cookie.getName(),cookieValue);
		}
		return cookieMap;
	}
}
